<?php
/**
 * Created by PhpStrom
 * User: 郭碧云
 * Date: 2021/3/15 14:18
 * Desc:
 */

namespace App\Models\Admin;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Spatie\Permission\Models\Permission as PermissionModel;
use Spatie\Permission\Traits\HasPermissions;


class Permission extends PermissionModel
{
    use HasPermissions;
    protected $table = 'permissions';
    protected $fillable=["name","guard_name","display_name","site_id","parent_id","type"];
    public $timestamps = true;    //自动管理时间戳
    protected $dateFormat = "U";  //时间样式




    protected $scopeLimit = false;//数据查询范围,设置为true时,数据查询将自动增加site_id条件
    protected $declares = [
        "name"=>["name","like"]
    ];

    public function __construct(array $attributes = []) {
        parent::__construct($attributes);
        //Todo 基类中获取站点ID方法,待检测确定
//        $this->site_id = Auth::guard('admin')->user()->site_id;
    }

    public function registerGlobalScopes($builder) {
        //自定义模型自动添加内置条件,可以通过 Model::withoutGlobalScope('site_id_scope')形式去除
        if ($this->scopeLimit && Schema::hasColumn($this->table, 'site_id') && getCurrentSiteId()) {
            static::addGlobalScope('site_id_scope', function (Builder $builder) {
                $siteId = getCurrentSiteId();
                $builder->where('site_id', '=', $siteId);
            });
        }

        foreach ($this->getGlobalScopes() as $identifier => $scope) {
            $builder->withGlobalScope($identifier, $scope);
        }
        return $builder;
    }

    /**
     * 判断模型中是否存在某字段
     * @param string $column
     * @return bool
     */
    public function hasColumn($column) {
        return Schema::hasColumn($this->table, $column);
    }

    /**
     * 统一条件传入
     * @param array|null $condition
     * @return mixed
     */
    public function whereBuilder(array $condition=null) {
        $where=[];
        if($condition) {
            foreach ($condition as $k => $v) {
                if (in_array($k, array_keys($this->declares))) {
                    $where[]=array_merge($this->declares[$k], [$v]);
                }
            }
        }
        return $this->where($where);
    }





    //列表
    public function getAll($where = []) {
        /*todo 需要修改*/
        return self::whereBuilder($where)->with('site')->orderBy("sort","asc")->get();

    }

    //重构权限添加功能
    public static function create(array $attributes = [])
    {
        return static::query()->create($attributes);
    }

    //权限是否存在
    public static function hasPermission($name,$site_id,$gurad_name){
        return self::where("name",$name)->where("site_id",$site_id)->where("guard_name",$gurad_name)->first();
    }

    //获取一个权限
    public function getOne($id){
        return self::find($id);
    }

    //修改权限
    public function change($params,$id){
        return self::where('id', $id)->update($params);
    }

    //获取权限详情
    public function info(Permission $permission){
        return self::with('site')->where("id",$permission->id)->first();
    }

    //修改权限可操作状态
    public function status($status,$id){
        return self::where("id", $id)->update(["status" => $status]);
    }

    //获取管理用户的所有权限
    public function get_per_list($guardName){
        /*站点管理的权限*/
        $site_id = getCurrentSiteId();
        if($site_id==0){
            $data = self::where("guard_name",$guardName)->where(function($query) use ($site_id) {
                $query->where("site_id",$site_id)->orWhere("site_id",0);
            })->get();
        }
        else{
            //获取当前用户下的所有权限
            $data = (new AdminUser())->find(getCurrentUser()["id"])->getAllPermissions();
        }
        return $data;
    }

    //获取有条件的权限
    public function terim($name,$site_id){
        return DB::select("select * from permissions where (site_id=? or site_id=?) and name=?",[$site_id,0,$name]);
    }



    //获取站点信息(多对一)
    public function site(){
        return $this->hasOne(Site::class,"id","site_id");
    }


}
